
/*

matrix drop _all
matrix results =[.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.]

foreach y in fam_asb {


	foreach term in ltav tyav {


		reg `y'_`term' tpassonly cashassonly tpcashass `controls' i.cg_strata ib55.tp_strata_alt
		estimates store `y'_`term'
		matrix X=r(table)
		mat lis X

		scalar b_tpass_`term'=X[1,1]
		scalar se_tpass_`term'=X[2,1]
		scalar pval_tpass_`term'=X[4,1]

		scalar b_cash_`term'=X[1,2]
		scalar se_cash_`term'=X[2,2]
		scalar pval_cash_`term'=X[4,2]

		scalar b_tpcash_`term'=X[1,3]
		scalar se_tpcash_`term'=X[2,3]
		scalar pval_tpcash_`term'=X[4,3]


		mat X_`y'_`term'=[b_tpass_`term',se_tpass_`term', pval_tpass_`term', b_cash_`term', se_cash_`term', pval_cash_`term', b_tpcash_`term', se_tpcash_`term', pval_tpcash_`term']
		*matrix rownames X_`y'_`term' = tpass cash tpcash  tpass cash tpcash  tpass cash tpcash
		mat lis X_`y'_`term'
	}

	suest `y'_ltav `y'_tyav

	test [`y'_ltav_mean]tpassonly=[`y'_tyav_mean]tpassonly
	scalar pvalue_1=r(p)

	test [`y'_ltav_mean]cashassonly=[`y'_tyav_mean]cashassonly
	scalar pvalue_2=r(p)

	test [`y'_ltav_mean]tpcashass=[`y'_tyav_mean]tpcashass
	scalar pvalue_3=r(p)

	mat pvalue_mat=[pvalue_1 , pvalue_2 , pvalue_3]

	mat X_`y'=X_`y'_ltav,  X_`y'_tyav , pvalue_mat
	*matrix colnames X_`y' = Estimate_lt Std_err Pvalue Estimate_9y Std_err Pvalue Pvalue_diff
	*matrix rownames X_`y' = `y'_tpass `y'cash `y'_tpcash
	matrix results=results\X_`y'
}





*/




cap program drop equation_test
program define equation_test
    set matsize 10000
    syntax  [if/], outcomevars(namelist) FILENAME(name) [controls(varlist)]


matrix drop _all


foreach y in `outcomevars' {


	foreach term in ltav tyav {


	 qui reg `y'_`term' tpassonly cashassonly tpcashass `controls' i.cg_strata ib55.tp_strata_alt
		qui estimates store `y'_`term'
		matrix X=r(table)
		*mat lis X

		scalar b_tpass_`term'=X[1,1]
		scalar se_tpass_`term'=X[2,1]
		scalar pval_tpass_`term'=X[4,1]

		scalar b_cash_`term'=X[1,2]
		scalar se_cash_`term'=X[2,2]
		scalar pval_cash_`term'=X[4,2]

		scalar b_tpcash_`term'=X[1,3]
		scalar se_tpcash_`term'=X[2,3]
		scalar pval_tpcash_`term'=X[4,3]


		mat X_`y'_`term'=[b_tpass_`term',se_tpass_`term', pval_tpass_`term', b_cash_`term', se_cash_`term', pval_cash_`term', b_tpcash_`term', se_tpcash_`term', pval_tpcash_`term']
		*matrix rownames X_`y'_`term' = tpass cash tpcash  tpass cash tpcash  tpass cash tpcash
		*mat lis X_`y'_`term'
	}

	qui suest `y'_ltav `y'_tyav

	qui test [`y'_ltav_mean]tpassonly=[`y'_tyav_mean]tpassonly
	scalar pvalue_1=r(p)

	qui test [`y'_ltav_mean]cashassonly=[`y'_tyav_mean]cashassonly
	scalar pvalue_2=r(p)

	qui test [`y'_ltav_mean]tpcashass=[`y'_tyav_mean]tpcashass
	scalar pvalue_3=r(p)

	mat pvalue_mat=[pvalue_1,.,.,pvalue_2,.,., pvalue_3,.,.]

	mat X_`y'=X_`y'_ltav,  X_`y'_tyav , pvalue_mat
	*matrix colnames X_`y' = Estimate_lt Std_err Pvalue Estimate_9y Std_err Pvalue Pvalue_diff
	matrix rownames X_`y' = `y'_tyav
	matrix results=nullmat(results)\X_`y'

}


qui frmttable, statmat(results) sdec(3) substat(2) varlabels

frmttable using outfiles/tables/`filename', varlabels ///
ctitle( " ", "1 yr Endline", " ", " ", "10 year Endline", " ", " ", "Difference", "", "" \ ///
        " ","\thead{Therapy \\ only}","\thead{Cash \\ only}","\thead{Both}", "\thead{Therapy \\ only}","\thead{Cash \\ only}","\thead{Both}",  "\thead{Therapy \\ p-val}" ,  "\thead{Cash \\ p-val}" ,  "\thead{Both \\ p-val}" \ ///
        " ", "(1)","(2)","(3)","(4)","(5)","(6)","(7)","(8)","(9)" ) ///
multicol(1,2,3;1,5,3;1,8,3) ///
tex fragment replace nocenter squarebrack

end








cap program drop round_test_reg
program define round_test_reg
    set matsize 10000
    syntax  [if/], outcomevars(namelist) treatvars(varlist) partid(varname) rounds(numlist) wavenames(namelist) roundvar(varname) wavevar(varname) ///
    				FILENAME(name) [controls(varlist) fixedeffects(varlist) clusterse(varlist)  repooled]

/*
   Ok, this function was desingned to compute temporal heterogeneity for treatment effects from multiple rounds.
   Although, this function can be used for other datasets and for overall heterogeneity; for purpose of this project this function with assume the following:


      * There is a time identifier which is define by roundvar
      * Time periods can also be identified by moments or waves which can have multiple survey rounds. Which is are identified by wavenames.
      * There are variables associated with each wave and are identified by a suffix in wavenames. This can be extended so the command does it for you.

  What this function is going to do:
      1. Create intertemporal interaction with treatment variables.
      2. Create round filters that will delimit sample in each regression.
      3. Set up a matrix template to export results.
      4. Compute one regression for each wave.
      5. If option repooled is specified, it will create a new outcome var that is the pooled version of wave associated variables.
      6. Compute a pooled regression with all specified waves and wave interactions with treatment effects.
      7. Save coefficients in matrix.
      8. Export output table to a latex format.


*/


*~~ Defining regression arguments ~~*

    if "`fixedeffects'"!="" local vfe abs(`fixedeffects')
    if "`fixedeffects'"=="" local vfe noa

    if "`clusterse'"!="" local vse vce(cluster `clusterse')
    if "`clusterse'"=="" local vse vce(r)


    if "`if'"!="" local ifa & `if'
    if "`if'"=="" local ifa

*~~ Creating interaction variables ~~*

    local int_vars
     foreach treat in `treatvars'{
       tempvar int_wave_`treat'
       gen `int_wave_`treat'' =  `treat' * `wavevar'
       local int_vars `int_vars' `int_wave_`treat''
     }

*~~ Defining temporal filters ~~*

    /*Since we have allowed for multiple rounds per wave, we will use the modulus command to associate each wave its respective first round
      When the modulus of the round number over the number of wave is equal to 1 over the number of waves it will create a local to associate waves and rounds. */

	tokenize `rounds'

	local roudspwave = `: word count `rounds'' / `: word count `wavenames''
	forvalues r = 1/`: word count `rounds''{
		local wavecount = ceil(`r' / `roudspwave')
		if mod(`r',`roudspwave') == 0 local round`: word `wavecount' of `wavenames'' = ``r''

	    if `r'==1 local ifrounds  ``r''
	    if `r'> 1 local ifrounds `ifrounds', ``r''
	}

	local ifrounds inlist(`roundvar',`ifrounds')

*~~ Building output matrix ~~*
	cap matrix drop results
	cap matrix drop stars

	local outcomenum : word count `outcomevars'
	matrix results = J(`outcomenum',33,.)
	matrix stars   = J(`outcomenum',33,0)

*~~ Computing regression and storing results ~~*

    /*There are three loops levels: (1) outcomes, (2) waves and (3) treatments.
      Each treatment will have a column and there is a column distance between each of 3 due to the 3 estimands stored: coeficcients, SE and p-vals.
      Each waves will be stored in columns and its distance is defined by =  (number of treatments * 3 + 3). Adding three more columns allows to store control variable mean.
      Each outcome will have a row and its row distance is 1.

      local poolout defines the treatment for the wave pooled regression. This regression assumas that  outcome variables with values for all waves/rounds. If not, option "repooled" can be use it
      to create such variable.
     */


	local loutcomevars
	local i = 1
	foreach y in `outcomevars' {

	local poolout `y'_e

	  local w = 0
		foreach term in `wavenames' {

	    qui sum `y'_`term'  if control == 1 & `roundvar' == `round`term'' `ifa'
	            mat results[`i',1 + `w'] = r(mean)

	      qui reghdfe `y'_`term' `treatvars' `controls' if `roundvar' == `round`term'' `ifa' , `vfe' `vse'

	               local t = 0
	            foreach treat in `treatvars' {
	            /* Recover Coefficients, standard errors, and p-values */

	                mat results[`i',4 + `t' + `w'] = _b[`treat']
	                mat results[`i',5 + `t' + `w'] = _se[`treat']
	                mat results[`i',6 + `t' + `w'] = 2*ttail(e(df_r),abs(_b[`treat']/_se[`treat']))

	                mat stars[`i',4 + `t' + `w'] = cond(results[`i',6 + `t' + `w'] <= .01,3,  ///
	                                               cond(results[`i',6 + `t' + `w'] <= .05,2,  ///
	                                               cond(results[`i',6 + `t' + `w'] <= .1,1,0  ///
	               )))
	                local t = `t' + 3
	            }
	    local w = `w' + (`: word count `treatvars'' * 3 + 3)
		}

	    if "`repooled'"!=""{
	       tempvar `y'_pooled
	       qui gen ``y'_pooled' = .
	         foreach term in `wavenames' {
	           qui replace ``y'_pooled' = `y'_`term' if `roundvar' == `round`term''
	         }
	         local poolout ``y'_pooled'
	    }

		 qui reghdfe `poolout' `int_vars' `treatvars' `wavevar' `controls'  if `ifrounds' `ifa' , `vfe' `vse'

	               local t = 0
	            foreach treat in `treatvars' {
	            /* Recover Coefficients, standard errors, and p-values */

	                mat results[`i',25 + `t']  =  _b[`int_wave_`treat'']
	                mat results[`i',26 + `t']  = _se[`int_wave_`treat'']
	                mat results[`i',27 + `t']  = 2*ttail(e(df_r),abs(_b[`int_wave_`treat''] / _se[`int_wave_`treat'']))

	                mat stars[`i',25 + `t'] = cond(results[`i',27 + `t'] <= .01,3,  ///
	                                          cond(results[`i',27 + `t'] <= .05,2,  ///
	                                          cond(results[`i',27 + `t'] <= .1,1,0  ///
	               )))
	                local t = `t' + 3
	            }
	  local loutcomevars  `loutcomevars' `y'_tyav
	  local ++i
	}

*~~ Exporting output ~~*

    /*frmttable with option substat(2) will traspose columns expects for the ones every 3*/

   matrix rownames results = `loutcomevars'

     frmttable, statmat(results) sdec(3) substat(2)
     qui frmttable, statmat(results) varlabels substat(2) sdec(3)  annotate(stars) asymbol(*,**,***)


frmttable using outfiles/tables/`filename', varlabels ///
ctitle(" ","\uline{\hfill 1 year \hfill}", "","","", "\uline{\hfill 10 year \hfill}","","","","\uline{\hfill Difference \hfill}","","" \ ///
       " ","\thead{Control \\ mean}","\thead{Therapy \\ Only}","\thead{Cash \\ Only}","\thead{Both}","\thead{Control \\ mean}","\thead{Therapy \\ Only}","\thead{Cash \\ Only}","\thead{Both}","\thead{Therapy \\ Only}","\thead{Cash \\ Only}","\thead{Both}"  \  ///
       " ", "(1)","(2)","(3)","(4)","(5)","(6)","(7)","(8)","(9)","(10)","(11)"   ) ///
tex fragment replace nocenter squarebrack   ///
multicol(1,2,4;1,6,4;1,10,3)


end





cap program drop round_test_reg_NSM
program define round_test_reg_NSM
    set matsize 10000
    syntax  [if/], outcomevars(namelist) treatvars(varlist) partid(varname) rounds(numlist) wavenames(namelist) roundvar(varname) wavevar(varname) ///
    				FILENAME(name) [controls(varlist) fixedeffects(varlist) clusterse(varlist)  repooled  col_0_title(string) ]

/*
   Ok, this function was desingned to compute temporal heterogeneity for treatment effects from multiple rounds.
   Although, this function can be used for other datasets and for overall heterogeneity; for purpose of this project this function with assume the following:


      * There is a time identifier which is define by roundvar
      * Time periods can also be identified by moments or waves which can have multiple survey rounds. Which is are identified by wavenames.
      * There are variables associated with each wave and are identified by a suffix in wavenames. This can be extended so the command does it for you.

  What this function is going to do:
      1. Create intertemporal interaction with treatment variables.
      2. Create round filters that will delimit sample in each regression.
      3. Set up a matrix template to export results.
      4. Compute one regression for each wave.
      5. If option repooled is specified, it will create a new outcome var that is the pooled version of wave associated variables.
      6. Compute a pooled regression with all specified waves and wave interactions with treatment effects.
      7. Save coefficients in matrix.
      8. Export output table to a latex format.


*/


*~~ Defining regression arguments ~~*

    if "`fixedeffects'"!="" local vfe abs(`fixedeffects')
    if "`fixedeffects'"=="" local vfe noa

    if "`clusterse'"!="" local vse vce(cluster `clusterse')
    if "`clusterse'"=="" local vse vce(r)


    if "`if'"!="" local ifa & `if'
    if "`if'"=="" local ifa

*~~ Creating interaction variables ~~*

    local int_vars
     foreach treat in `treatvars'{
       tempvar int_wave_`treat'
       gen `int_wave_`treat'' =  `treat' * `wavevar'
       local int_vars `int_vars' `int_wave_`treat''
     }

*~~ Defining temporal filters ~~*

    /*Since we have allowed for multiple rounds per wave, we will use the modulus command to associate each wave its respective first round
      When the modulus of the round number over the number of wave is equal to 1 over the number of waves it will create a local to associate waves and rounds. */

	tokenize `rounds'

	local roudspwave = `: word count `rounds'' / `: word count `wavenames''
	forvalues r = 1/`: word count `rounds''{
		local wavecount = ceil(`r' / `roudspwave')
		if mod(`r',`roudspwave') == 0 local round`: word `wavecount' of `wavenames'' = ``r''

	    if `r'==1 local ifrounds  ``r''
	    if `r'> 1 local ifrounds `ifrounds', ``r''
	}

	local ifrounds inlist(`roundvar',`ifrounds')

*~~ Building output matrix ~~*
	cap matrix drop results
	cap matrix drop stars

	local outcomenum : word count `outcomevars'
	matrix results = J(`outcomenum',39,.)
	matrix stars   = J(`outcomenum',39,0)

*~~ Computing regression and storing results ~~*

    /*There are three loops levels: (1) outcomes, (2) waves and (3) treatments.
      Each treatment will have a column and there is a column distance between each of 3 due to the 3 estimands stored: coeficcients, SE and p-vals.
      Each waves will be stored in columns and its distance is defined by =  (number of treatments * 3 + 3). Adding three more columns allows to store control variable mean.
      Each outcome will have a row and its row distance is 1.

      local poolout defines the treatment for the wave pooled regression. This regression assumas that  outcome variables with values for all waves/rounds. If not, option "repooled" can be use it
      to create such variable.
     */


	local loutcomevars
	local i = 1
	foreach y in `outcomevars' {

	qui summ `y'_tyav if `if', d
            if `r(N)' {


	local poolout `y'_e

	  local w = 0

		foreach term in `wavenames' {


	      qui reghdfe `y'_`term' `treatvars' `controls' if `roundvar' == `round`term'' `ifa' , `vfe' `vse'

	               local t = 0
	            foreach treat in `treatvars' {
	            /* Recover Coefficients, standard errors, and p-values */

	                mat results[`i', 1 + `t' + `w'] = _b[`treat']
	                mat results[`i', 2 + `t' + `w'] = _se[`treat']
	                mat results[`i', 3 + `t' + `w'] = 2*ttail(e(df_r),abs(_b[`treat']/_se[`treat']))

	                mat stars[`i', 1 + `t' + `w'] = cond(results[`i',3 + `t' + `w'] <= .01,3,  ///
	                                               cond(results[`i',3 + `t' + `w'] <= .05,2,  ///
	                                               cond(results[`i',3 + `t' + `w'] <= .1,1,0  ///
	               )))

	                local t = `t' + 3
	            }
	    local w = `w' + (`: word count `treatvars'' * 3 + 6)
		}

	    if "`repooled'"!=""{
	       tempvar `y'_pooled
	       qui gen ``y'_pooled' = .
	         foreach term in `wavenames' {
	           qui replace ``y'_pooled' = `y'_`term' if `roundvar' == `round`term''
	         }
	         local poolout ``y'_pooled'
	    }

		 qui reghdfe `poolout' `int_vars' `treatvars' `wavevar' `controls'  if `ifrounds' `ifa' , `vfe' `vse'

	               local t = 0
	            foreach treat in `treatvars' {
	            /* Recover Coefficients, standard errors, and p-values */

	                mat results[`i', 31 + `t']  =  _b[`int_wave_`treat'']
	                mat results[`i', 32 + `t']  = _se[`int_wave_`treat'']
	                mat results[`i', 33 + `t']  = 2*ttail(e(df_r),abs(_b[`int_wave_`treat''] / _se[`int_wave_`treat'']))

	                mat stars[`i', 31 + `t'] = cond(results[`i',33 + `t'] <= .01,3,  ///
	                                          cond(results[`i',33 + `t'] <= .05,2,  ///
	                                          cond(results[`i',33 + `t'] <= .1,1,0  ///
	               )))
	                local t = `t' + 3
	            }

	        }
	  local loutcomevars  `loutcomevars' `y'_tyav
	  local ++i
	}

*~~ Exporting output ~~*

    /*frmttable with option substat(2) will traspose columns expects for the ones every 3*/

   matrix rownames results = `loutcomevars'

     frmttable, statmat(results) sdec(3) substat(2)
     qui frmttable, statmat(results) varlabels substat(2) sdec(3)  annotate(stars) asymbol(*,**,***)


frmttable using outfiles/tables/`filename', varlabels ///
ctitle(" ","\uline{\hfill 1- year \hfill}", "","", "","", "\uline{\hfill 10- year \hfill}","","","","", "\uline{\hfill 1- vs 10-year difference \hfill}","","" \ ///
       "`col_0_title'","\thead{Therapy \\ Only}","\thead{Cash \\ Only}","\thead{Both}", "", "", "\thead{Therapy \\ Only}","\thead{Cash \\ Only}","\thead{Both}", "", "","\thead{Therapy \\ Only}","\thead{Cash \\ Only}","\thead{Both}"  \  ///
       " ", "(1)","(2)","(3)", "", "", "(4)","(5)","(6)", "", "", "(7)","(8)","(9)"   ) ///
tex fragment replace nocenter squarebrack   ///
multicol(1,2,3;1,7,3;1,12,3)


end











cap program drop het_test_reg
program define het_test_reg
    set matsize 10000
    syntax  [if/], outcomevars(namelist) treatvars(varlist) rounds(numlist) roundvar(varname) wavevar(varname) FILENAME(name) [controls(varlist) fixedeffects(varlist) ]


*~~ Defining regression arguments ~~*

    if "`fixedeffects'"!="" local vfe abs(`fixedeffects')
    if "`fixedeffects'"=="" local vfe noa

    if "`if'"!="" local ifa & `if'
    if "`if'"=="" local ifa

*~~ Creating interaction variables ~~*

    local int_vars
     foreach treat in `treatvars'{
       tempvar int_wave_`treat'
       gen `int_wave_`treat'' =  `treat' * `wavevar'
       local int_vars `int_vars' `int_wave_`treat''
     }

*~~ Defining temporal filters ~~*

    /*Since we have allowed for multiple rounds per wave, we will use the modulus command to associate each wave its respective first round
      When the modulus of the round number over the number of wave is equal to 1 over the number of waves it will create a local to associate waves and rounds. */

	tokenize `rounds'

	forvalues r = 1/`: word count `rounds''{

	    if `r'==1 local ifrounds  ``r''
	    if `r'> 1 local ifrounds `ifrounds', ``r''
	}

	local ifrounds inlist(`roundvar',`ifrounds')

*~~ Building output matrix ~~*
	cap matrix drop results
	cap matrix drop stars

	local outcomenum : word count `outcomevars'
	local columnnum  = ((`: word count `treatvars'' * 2) + 1) * 3
	matrix results = J(`outcomenum',`columnnum',.)
	matrix stars   = J(`outcomenum',`columnnum',0)

*~~ Computing regression and storing results ~~*

	local loutcomevars
	local i = 1
	foreach y in `outcomevars' {

		qui reghdfe `y'_e `int_vars' `treatvars' `wavevar' `controls'  if `ifrounds' `ifa' , `vfe'

                local t = 0
	            foreach treat in `wavevar' `treatvars' `int_vars' {
	            /* Recover Coefficients, standard errors, and p-values */

	                mat results[`i',1 + `t' ] = _b[`treat']
	                mat results[`i',2 + `t' ] = _se[`treat']
	                mat results[`i',3 + `t' ] = 2*ttail(e(df_r),abs(_b[`treat']/_se[`treat']))

	                mat stars[`i',1 + `t'] = cond(results[`i',3 + `t' ] <= .01,3,  ///
	                                               cond(results[`i',3 + `t' ] <= .05,2,  ///
	                                               cond(results[`i',3 + `t' ] <= .1,1,0  ///
	               )))

	                local t = `t' + 3

	            }


	  local loutcomevars  `loutcomevars' `y'_e
	  local ++i
	}

*~~ Exporting output ~~*

    /*frmttable with option substat(2) will traspose columns expects for the ones every 3*/

   matrix rownames results = `loutcomevars'

     frmttable, statmat(results) sdec(3) substat(2)
     qui frmttable, statmat(results) varlabels substat(2) sdec(3)  annotate(stars) asymbol(*,**,***)


frmttable using outfiles/tables/`filename', varlabels ///
ctitle(" ","", "\uline{\hfill 10-years \hfill}","","","\uline{\hfill Difference \hfill}","","" \ ///
       " ","\thead{1 year endline}","\thead{Therapy \\ only}","\thead{Cash \\ only}","\thead{Both}","\thead{Therapy \\ only}","\thead{Cash \\ only}","\thead{Both}"  \  ///
       " ", "(1)","(2)","(3)","(4)","(5)","(6)","(7)"  ) ///
tex fragment replace nocenter squarebrack   ///
multicol(1,3,3;1,6,3)


end
